package com.snack.shop.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.snack.shop.common.Result;
import com.snack.shop.dto.FeedbackSubmitRequest;
import com.snack.shop.dto.FeedbackAppendRequest;
import com.snack.shop.dto.FeedbackReplyRequest;
import com.snack.shop.entity.Feedback;
import com.snack.shop.entity.FeedbackReply;
import com.snack.shop.service.FeedbackService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 意见反馈控制器
 */
@Tag(name = "意见反馈")
@RestController
@RequestMapping("/feedback")
@RequiredArgsConstructor
public class FeedbackController {

    private final FeedbackService feedbackService;

    @Operation(summary = "提交反馈")
    @PostMapping("/submit")
    public Result<Feedback> submitFeedback(@Validated @RequestBody FeedbackSubmitRequest request) {
        Long userId = StpUtil.getLoginIdAsLong();
        Feedback feedback = feedbackService.submitFeedback(userId, request);
        return Result.success(feedback);
    }

    @Operation(summary = "获取我的反馈列表")
    @GetMapping("/list")
    public Result<Page<Feedback>> getFeedbackList(
            @Parameter(description = "反馈状态（null表示全部，0-待处理，1-处理中，2-已处理，3-已关闭）") @RequestParam(required = false, defaultValue = "") String status,
            @Parameter(description = "当前页") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer pageSize
    ) {
        Long userId = StpUtil.getLoginIdAsLong();
        Integer statusValue = null;
        if (status != null && !status.isEmpty() && !"null".equals(status)) {
            try {
                statusValue = Integer.parseInt(status);
            } catch (NumberFormatException e) {
                statusValue = null;
            }
        }
        Page<Feedback> page = feedbackService.getUserFeedbackPage(userId, statusValue, pageNum, pageSize);
        return Result.success(page);
    }

    @Operation(summary = "获取反馈详情")
    @GetMapping("/{id}")
    public Result<Feedback> getFeedbackDetail(@PathVariable Long id) {
        Long userId = StpUtil.getLoginIdAsLong();
        Feedback feedback = feedbackService.getFeedbackDetail(id, userId);
        
        // 标记为已读
        feedbackService.markAsRead(id, userId);
        
        return Result.success(feedback);
    }

    @Operation(summary = "获取反馈回复列表")
    @GetMapping("/{id}/replies")
    public Result<List<FeedbackReply>> getFeedbackReplies(@PathVariable Long id) {
        List<FeedbackReply> replies = feedbackService.getFeedbackReplies(id);
        return Result.success(replies);
    }

    @Operation(summary = "追加反馈")
    @PostMapping("/{id}/append")
    public Result<Void> appendFeedback(
            @PathVariable Long id,
            @Validated @RequestBody FeedbackAppendRequest request
    ) {
        Long userId = StpUtil.getLoginIdAsLong();
        feedbackService.appendFeedback(userId, id, request);
        return Result.success();
    }

    @Operation(summary = "管理端：获取反馈列表")
    @SaCheckRole("merchant")
    @GetMapping("/admin/list")
    public Result<Page<Feedback>> getAdminFeedbackList(
            @Parameter(description = "反馈类型（null表示全部）") @RequestParam(required = false, defaultValue = "") String type,
            @Parameter(description = "反馈状态（null表示全部）") @RequestParam(required = false, defaultValue = "") String status,
            @Parameter(description = "当前页") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer pageSize
    ) {
        Integer typeValue = null;
        if (type != null && !type.isEmpty() && !"null".equals(type)) {
            try {
                typeValue = Integer.parseInt(type);
            } catch (NumberFormatException e) {
                typeValue = null;
            }
        }
        
        Integer statusValue = null;
        if (status != null && !status.isEmpty() && !"null".equals(status)) {
            try {
                statusValue = Integer.parseInt(status);
            } catch (NumberFormatException e) {
                statusValue = null;
            }
        }
        
        Page<Feedback> page = feedbackService.getAdminFeedbackPage(typeValue, statusValue, pageNum, pageSize);
        return Result.success(page);
    }

    @Operation(summary = "管理端：更新反馈状态")
    @SaCheckRole("merchant")
    @PostMapping("/{id}/status")
    public Result<Void> updateFeedbackStatus(
            @PathVariable Long id,
            @Parameter(description = "新状态：0-待处理，1-处理中，2-已处理，3-已关闭") @RequestParam Integer status
    ) {
        feedbackService.updateFeedbackStatus(id, status);
        return Result.success();
    }

    @Operation(summary = "管理端：回复反馈")
    @SaCheckRole("merchant")
    @PostMapping("/{id}/reply")
    public Result<Void> replyFeedback(
            @PathVariable Long id,
            @Validated @RequestBody FeedbackReplyRequest request
    ) {
        Long handlerId = StpUtil.getLoginIdAsLong();
        feedbackService.replyFeedback(id, handlerId, request);
        return Result.success();
    }
}
